<template lang="pug">
  el-dialog(v-bind:visible="visible"
  v-bind:before-close="close"
  v-bind:close-on-click-modal="false"
  v-bind:append-to-body="true"
  width="500px")
    div.tit(slot="title") 用户登录
    el-form.form(ref="dialogForm" v-bind:model="formModel")
      el-form-item(label="" prop="username" v-bind:rules="rules.phone")
        el-input(v-model="formModel.username" placeholder="账号 / 手机号码")
      el-form-item(label="" prop="password" v-bind:rules="rules.password")
        el-input(v-model="formModel.password" type="password" placeholder="登录密码")
      div
        el-button.btn-login(v-on:click="onLogin" type="primary") 立即登录
</template>
<script type="text/ecmascript-6">
  import {baseURL} from '@/config/global.toml'
  import Cache from 'kalix-vue-common/src/common/cache'

  export default {
    data() {
      return {
        visible: false,
        randomMessage: '',
        random: '',
        formModel: {
          username: '',
          password: ''
        },
        rules: {
          phone: [{required: true, message: '请输入用户名', trigger: 'blur'}],
          password: [{required: true, message: '请输入密码', trigger: 'blur'}]
        }
      }
    },
    mounted() {
      this.getRandomImg()
    },
    methods: {
      onLogin() {
        this.$refs.dialogForm.validate((valid) => {
          if (valid) {
            this.$http.request({
              method: 'POST',
              url: `webapp/user/login`,
              params: {
                account: this.formModel.username,
                password: this.formModel.password
              }
            }).then(res => {
              if (res.data.success) {
                Cache.save('entity', res.data.entity)
              }
            })
          }
        })
      },
      getRandomImg() {
        this.icode = Math.random()
        this.random = `${baseURL}/webapp/user/imgCode?iCode=${this.icode}`
      },
      open() {
        this.visible = true
      },
      close() {
        this.visible = false
      }
    }
  }
</script>
<style scoped lang="stylus" type="text/stylus">
  .tit
    text-align center
  .form
    width 300px
    margin 0 auto
    .btn-login
      width 100%
</style>
